﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using AMM.CustomWinControls;
using AMM.Model;

namespace AMM.CommonControls {
    public class AMMDataGridViewAllowEdit : DataGridViewEx {

        private List<object> _deleteList;
        private BindingSource _bs;
        private ContextMenuStrip _menu;

        protected override void OnColumnNameChanged(DataGridViewColumnEventArgs e) {
            base.OnColumnNameChanged(e);
            if (e.Column.HeaderText.StartsWith("E")) {
                e.Column.HeaderText = e.Column.HeaderText.Replace("E", string.Empty);
            }
            else {
                e.Column.HeaderCell.Style.ForeColor = Color.Red;
                e.Column.HeaderCell.ToolTipText = "必填项";
            }
        }

        protected override void OnDataError(bool displayErrorDialogIfNoHandler, DataGridViewDataErrorEventArgs e) {
            e.Cancel = false;
            e.ThrowException = false;
            this.CurrentCell.ErrorText = "数据格式错误，系统自动显示最后一次正确输入的值或者缺省值！";
            base.OnDataError(e.ThrowException, e);
        }

        protected override void OnCellValidating(DataGridViewCellValidatingEventArgs e) {
            if (!string.IsNullOrEmpty(this.CurrentCell.OwningColumn.HeaderCell.ToolTipText)) {
                this.CurrentCell.ErrorText = e.FormattedValue == null || string.IsNullOrEmpty(e.FormattedValue.ToString())
                    ? this.CurrentCell.OwningColumn.HeaderCell.ToolTipText
                    : string.Empty;
            }
            base.OnCellValidating(e);
        }

        protected override void OnCellBeginEdit(DataGridViewCellCancelEventArgs e) {
            base.OnCellBeginEdit(e);
            this.CurrentCell.ErrorText = string.Empty;
        }



        /*
        protected override void OnCellClick(DataGridViewCellEventArgs e) {
            if (e.ColumnIndex == -1 || e.RowIndex == -1) { return; }

            DataGridViewCell currentCell = this[e.ColumnIndex, e.RowIndex];
            if (!currentCell.ReadOnly && currentCell.Visible) {
                this.BeginEdit(true);

                DataGridViewColumn currentColumn = this.Columns[e.ColumnIndex];
                if (currentColumn is DataGridViewComboBoxColumn) {
                    ((ComboBox)this.EditingControl).DroppedDown = true;
                }
                else if (currentColumn is DataGridViewSelfColumnEx) {
                    ((DataGridViewDropDownEx)this.EditingControl).DroppedDownEx = true;
                }
                else if (currentColumn is DataGridViewDateTimePickerColumnEx) {
                    SendKeys.Send("%{DOWN}");
                }

            }

            base.OnCellClick(e);
        }
        */

        public AMMDataGridViewAllowEdit() {
            this._menu = new ContextMenuStrip();
            this._deleteList = new List<object>();

            ToolStripMenuItem menuAdd = new ToolStripMenuItem("添加", null, (s, e) => {
                object objInstance = this._bs.AddNew();
                ((BaseModel)objInstance).ClassStatus = ClassStatus.Added;
            });
            menuAdd.Name = "menuItemAdd";

            ToolStripMenuItem menuInsert = new ToolStripMenuItem("插入", null, (s, e) => {
                Type type = this._bs.Current.GetType();
                object objInstance = Assembly.GetAssembly(type).CreateInstance(type.ToString());
                ((BaseModel)objInstance).ClassStatus = ClassStatus.Added;
                this._bs.Insert(this._bs.Position, objInstance);
            });
            menuInsert.Name = "menuItemInsert";

            ToolStripMenuItem menuDelete = new ToolStripMenuItem("删除", null, (s, e) => {
                BaseModel objInstance = (BaseModel)this._bs.Current;
                if (objInstance.ClassStatus != ClassStatus.Added) {
                    objInstance.ClassStatus = ClassStatus.Deleted;
                    this._deleteList.Add(objInstance);
                }
                this._bs.RemoveCurrent();
            });
            menuDelete.Name = "menuItemDelete";

            this._menu.Items.Add(menuAdd);
            this._menu.Items.Add(menuInsert);
            this._menu.Items.Add(menuDelete);

            this.ContextMenuStrip = this._menu;
            this.AutoGenerateColumns = false;
            this.IsShowRowHeaderNumberEx = true;
            this.IsClearSelectionWhenLeaveEx = true;
            this.EnableHeadersVisualStyles = false;
            this.EditMode = DataGridViewEditMode.EditOnEnter;
        }

        public object DataSourceEx {
            set {
                this._bs = new BindingSource();
                this._bs.ListChanged += new ListChangedEventHandler((s, e) => {
                    this._menu.Items["menuItemInsert"].Enabled =
                        this._menu.Items["menuItemDelete"].Enabled = this._bs.Count != 0;
                    // only need to mark Changed event
                    if (e.ListChangedType == ListChangedType.ItemChanged) {
                        BaseModel objInstance = (BaseModel)this._bs.Current;
                        if (objInstance.ClassStatus != ClassStatus.Added) {
                            objInstance.ClassStatus = ClassStatus.Updated;
                        }
                    }
                });
                this._bs.DataSource = value;
                this.DataSource = this._bs;
            }
        }

        public List<T> GetDataSourceEx<T>(bool isIncludeDeleteObjects = true) {
            List<T> ds = (List<T>)this._bs.DataSource;
            if (isIncludeDeleteObjects) {
                List<T> dsDelete = this._deleteList.Cast<T>().ToList();
                ds.AddRange(dsDelete);
            }
            this._deleteList.Clear();
            return ds;
        }
    }
}
